//
//  PPPictureLoadingProgressView.m
//  pickpic
//
//  Created by Jinxiao on 11/6/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPPictureLoadingProgressView.h"

@interface PPPictureLoadingProgressView ()
@property (readwrite, nonatomic, strong) CAShapeLayer *trackLayer;
@property (readwrite, nonatomic, strong) CAShapeLayer *valueLayer;
@end

#define degreesToRadians(x) (M_PI*(x)/180.0)

@implementation PPPictureLoadingProgressView

- (instancetype)init {
    self = [super init];

    
    
    _size = CGSizeMake(kProgressSize, kProgressSize);

    _trackColor = [UIColor colorWithRGBHex:0x1a1a1a];
//    _valueColor = [UIColor colorWithRGBHex:0x262626];

    _trackLayer = [CAShapeLayer layer];
    _trackLayer.lineCap = kCALineCapButt;
    _trackLayer.lineWidth = 3;
    _trackLayer.lineJoin = kCALineJoinRound;
    _trackLayer.strokeEnd = 1;
    _trackLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:_trackLayer];

    _valueLayer = [CAShapeLayer layer];
    _valueLayer.lineCap = kCALineCapButt;
    _valueLayer.lineWidth = _trackLayer.lineWidth;
    _valueLayer.lineJoin = kCALineJoinRound;
    _valueLayer.strokeEnd = 0;
    _valueLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:_valueLayer];

    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _trackLayer.frame = self.bounds;
    _trackLayer.strokeColor = _trackColor.CGColor;

    _valueLayer.frame = self.bounds;
    _valueLayer.strokeColor = _valueColor.CGColor;

    UIBezierPath *trackPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.width/2, self.height/2) radius:(self.width - _trackLayer.lineWidth)/2 startAngle:degreesToRadians(-90) endAngle:degreesToRadians(270) clockwise:YES];
    UIBezierPath *valuePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.width/2, self.height/2) radius:(self.width - _valueLayer.lineWidth)/2 startAngle:degreesToRadians(-90) endAngle:degreesToRadians(270) clockwise:YES];

    _trackLayer.path = trackPath.CGPath;
    _valueLayer.path = valuePath.CGPath;

    _valueLayer.strokeEnd = _progress;
}

- (void)setTrackColor:(UIColor *)trackColor {
    _trackColor = trackColor;

    [self setNeedsLayout];
}

- (void)setValueColor:(UIColor *)valueColor {
    _valueColor = valueColor;

    [self setNeedsLayout];
}

- (void)setProgress:(double)progress {
    _progress = progress;

//    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
//    pathAnimation.duration = 1;
//    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.6 :0.0 :0.4 :1];
//    pathAnimation.fromValue = @(_valueLayer.strokeEnd);
//    pathAnimation.toValue = @(progress);
//    [_valueLayer addAnimation:pathAnimation forKey:@"path"];

    [self setNeedsLayout];
}
@end
